<template>
  <div>
    <div class="content">
      <el-form ref="ruleFormRef" :model="state" status-icon :rules="passwordInfoRules" label-width="120px"
        class="demo-ruleForm">
        <el-form-item label="原密码" prop="old_password">
          <el-input v-model="state.old_password" type="password" show-password autocomplete="off" :prefix-icon="Lock"
            clearable />
        </el-form-item>
        <el-form-item label="新密码" prop="new_password">
          <el-input v-model="state.new_password" type="password" show-password autocomplete="off" :prefix-icon="Lock"
            clearable />
        </el-form-item>
        <el-form-item label="确认密码" prop="check_password">
          <el-input v-model="state.check_password" type="password" show-password autocomplete="off" clearable
            :prefix-icon="Lock" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="goBack">返回</el-button>
          <el-button type="primary" @click="submitForm(ruleFormRef)">确认</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import type { FormInstance } from 'element-plus'
import { Lock } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { useUserInfoStore } from '@/stores/info/index'
import SsoUserApi from '@/api/sso_user'
import type { SsoUser } from '@/api/sso_user/type'
import { encryptedData } from '@/utils/jsencrypt'

const router = useRouter()
const userInfoStore = useUserInfoStore()

interface PasswordState {
  old_password: string
  new_password: string
  check_password: string
}

const state = reactive<PasswordState>({
  old_password: '',
  new_password: '',
  check_password: ''
})


// 检查原密码
const checkOldPassword = async (_rule: any, value: string, callback: any) => {
  if (value === '') {
    callback(new Error('请输入原始密码'))
  } else {
    try {
      const res = await SsoUserApi.getUser(userInfoStore.userInfo.user_id)
      if (Array.isArray(res.data) && res.data.length > 0) {
      // 获取数组的第一个元素
      const Data = res.data[0]
      console.log('VALUE',value)
      if ( Data.password === value) {
        callback()
      } else {
        callback(new Error('原始密码错误'))
      }
    } }catch (error) {
      console.error('验证原密码失败:', error)
      callback(new Error('验证原密码失败'))
    }
  }
}

// 检查新密码
const checkNewPassword = (_rule: any, value: string, callback: any) => {
  if (value === '') {
    callback(new Error('请输入新密码'))
  } else if (value === state.old_password) {
    callback(new Error('新密码不能与原密码相同'))
  } else {
    if (state.check_password !== '') {
      ruleFormRef.value?.validateField('check_password')
    }
    callback()
  }
}

// 确认密码
const validateCheckPassword = (_rule: any, value: string, callback: any) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== state.new_password) {
    callback(new Error('两次输入密码不一致！'))
  } else {
    callback()
  }
}

const ruleFormRef = ref<FormInstance>()
const passwordInfoRules = reactive({
  old_password: [{ validator: checkOldPassword, trigger: 'blur' }],
  new_password: [{ validator: checkNewPassword, trigger: 'blur' }],
  check_password: [{ validator: validateCheckPassword, trigger: 'blur' }]
})

// 返回
const goBack = () => {
  router.push({
    name: 'counselorSettings'
  })
}

// 提交修改
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (valid) {
      try {
        const updateData: Partial<SsoUser> = {
          user_id: userInfoStore.userInfo.user_id,
          password: String(encryptedData(state.new_password))
        }

        await SsoUserApi.updateUser(userInfoStore.userInfo.user_id, updateData)
        ElMessage.success('密码修改成功，请重新登录')
        
        // 清除登录状态
        userInfoStore.setIsLogin(false)
        
        // 跳转到登录页
        router.push({
          path:'/login/login'
        })
      } catch (error) {
        console.error('修改密码失败:', error)
        ElMessage.error('修改密码失败')
      }
    }
  })
}
</script>

<style scoped>
.content {
  width: 100%;
  height: 300px;
  margin: 100px auto;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.el-form-item {
  margin-bottom: 30px;
}
</style>
